package com.woniu.service.impl;

import com.woniu.dto.DrugDistributionDto;
import com.woniu.entity.Drug;
import com.woniu.entity.DrugDistribution;
import com.woniu.entity.MedicineDetail;
import com.woniu.mapper.DrugDistributionMapper;
import com.woniu.mapper.DrugMapper;
import com.woniu.mapper.MedicineDetailMapper;
import com.woniu.service.DrugDistributeService;
import com.woniu.utils.ResponseEnum;
import com.woniu.utils.ResponseUtil;
import com.woniu.utils.SnowflakeIdGenerator;
import com.woniu.vo.DrugDistributionVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: zcy
 * @Create: 2025/11/3 14:38
 */
@Service
public class DrugDistributeServiceImpl implements DrugDistributeService {
    @Resource
    private DrugDistributionMapper drugDistributionMapper;
    @Resource
    private DrugMapper drugMapper;
    @Resource
    private MedicineDetailMapper medicineDetailMapper;
    @Override
    public ResponseUtil add(DrugDistributionDto drugDistributionDto) throws InterruptedException {
        String drugName = drugDistributionDto.getDrugName();
        Drug drug = drugMapper.findByName(drugName);
        if ( drug.getDsStock() < drugDistributionDto.getQuantity()) {
            return ResponseUtil.get(ResponseEnum.DRUG_STOCK_NOT_ENOUGH);
        }
        SnowflakeIdGenerator sfg = new SnowflakeIdGenerator();
        String s = String.valueOf(sfg.nextId());
        DrugDistribution drugDistribution = new DrugDistribution();
        drugDistribution.setPpNo(s);
        drugDistribution.setPpCaseid(drugDistributionDto.getPpCaseid());
        drugDistribution.setPpWorkerid(drugDistributionDto.getPpWorkerid());
        drugDistribution.setPpDate(new Date(System.currentTimeMillis()));
        drugDistribution.setPpStatus("0");
        drugDistribution.setPpType("0");
        int insert = drugDistributionMapper.insert(drugDistribution);
        if(insert <=0){
            return ResponseUtil.get(ResponseEnum.FAIL);
        }
        MedicineDetail medicineDetail = new MedicineDetail();
//        medicineDetail.setMdPrescriptionid(s);
        medicineDetail.setMdDrugstoreid(drug.getId());
        medicineDetail.setMdName(drugName);
        medicineDetail.setMdNum(drugDistributionDto.getQuantity());
        medicineDetail.setMdBuyprice(drug.getDsOutprice());
        int insert1 = medicineDetailMapper.insert(medicineDetail);

        drug.setDsStock(drug.getDsStock() - drugDistributionDto.getQuantity());
        drugMapper.updateByPrimaryKey(drug);
        return insert1 > 0 ?
                ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }



}
